<?php
class UsersController extends AppController {

    public $name = 'Users';
    public $helpers = array('Text');
    public function beforeFilter(){
        parent::beforeFilter();
        $this->Auth->allow('home', 'login');
    }

    /* User.dashborad, which is the home page for all logged in users */
    public function dashboard(){}

    /* Website home, which is open to nobody, website home page */
    public function home(){
        $this->loadModel('PostTerm');
        $this->PostTerm->recursive = 1;
        $terms = $this->PostTerm->find('all');

        $this->loadModel('Company');
        $companies = $this->Company->find('all');

        $this->loadModel('Job');
        $jobs = $this->Job->find('all');

        $this->set(compact('terms', 'companies', 'jobs'));
    }

    public function login(){
        if($this->Auth->user()){
            if(!empty($this->data)){
                if(empty($this->data['User']['remember_me'])){
                    $this->Cookie->del('User');
                }else{
                    $cookie = array();
                    $cookie['username'] = $this->data['User']['username'];
                    $cookie['password'] = $this->data['User']['password'];
                    $this->Cookie->write('User', $cookie, true, '+2 weeks');
                }
                unset($this->data['User']['remember_me']);
            }
            $this->redirect($this->Auth->redirect());
        }else{
            $this->redirect(array('action'=>'home'));
        }
    }
    public function logout(){
        $cookie = $this->Cookie->read('User');
        if($cookie){
            $this->Cookie->del('User');
        }
        $this->Session->setFlash(__('You have Logged out', true));
        $this->redirect($this->Auth->logout());
    }

    /* User data administration index page */
    public function index(){
        $this->User->recursive = 0;
        $this->set('users', $this->paginate());
        $this->set('groups', $this->Group->find('list'));
    }

    public function view($id = null){
        if(!$id){
            $this->Session->setFlash(__('Invalid User.', true));
            $this->redirect(array('action'=>'index'));
        }
        $this->set('user', $this->User->read(null, $id));
    }

    public function add(){
        if(!empty($this->data)){
            $this->User->create();
            if($this->User->save($this->data)){
                $this->Session->setFlash(__('The User has been saved', true));
            }else{
                $this->Session->setFlash(__('The User could not be saved. Please, try again.', true));
                $this->data = null;
            }
        }
        /* Redirect to user index page after add, no matter success or failed */
        $this->redirect(array('action'=>'index'));
    }

    public function edit($id = null){
        if(!$id && empty($this->data)){
            $this->Session->setFlash(__('Invalid User', true));
            $this->redirect(array('action'=>'index'));
        }
        if(!empty($this->data)){
            if($this->User->save($this->data)){
                $this->Session->setFlash(__('The User has been saved', true));
                $this->redirect(array('action'=>'index'));
            }else{
                $this->Session->setFlash(__('The User could not be saved. Please, try again.', true));
            }
        }
        if(empty($this->data)){
            $this->data = $this->User->read(null, $id);
        }
        // for the parent group
        $groups = $this->User->Group->find('list');
        $this->set('groups', $groups);
    }

    public function delete($id = null){
        if(!$id){
            $this->Session->setFlash(__('Invalid id for User', true));
            $this->redirect(array('action'=>'index'));
        }
        if($this->User->del($id)){
            $this->Session->setFlash(__('User deleted', true));
            $this->redirect(array('action'=>'index'));
        }
    }

    public function check(){
        if(!empty($this->data)){
            $user = $this->User->findByUsername($this->data['User']['username']);
            if(empty($user['User']['username'])){
                $this->Response->json(true, 'User name check success', $user, null);
            }else{
                $this->Response->json(false, 'User name check failure', $user['User']['username'], null);
            }
        }else{
            $this->Response->json(false, 'Invalid User name check request', null, null);
        }
    }

    public function password(){
        if(!empty($this->data)){
            $this->User->id = $this->user['id'];
            $pwd = $this->Auth->password($this->data['User']['newpassword']);
            if($this->User->saveField('password', $pwd)){
                $this->Session->setFlash(__('New passwords has been saved, please login with the new password', true));
            }else{
                $this->Session->setFlash(__('Passwords cannot be saved, please try again', true));
            }
        }
    }

    public function security($id){
        /* Redirect on invalid security request */
        if(!$id && empty($this->data)){
            $this->Session->setFlash(__('Invalid Group', true));
            $this->redirect(array('action'=>'index'));
        }
        /* Save changes and redirect to Index page */
        if(!empty($this->data)){
            // lets get the Aro i.e. the group
            $aro_foreign_key = $this->data['User']['id'];
            $aro =& $this->Acl->Aro;
            $aro_record = $aro->findByAlias('User:'.$aro_foreign_key);
            $aro_alias = $aro_record['Aro']['alias'];
            $aco_of_aro = $aro_record['Aco'];
            // lets run through the security selection
            $sec_access = $this->data['User']['SecurityAccess'];
            $aco =& $this->Acl->Aco;
            foreach ($sec_access as $aco_id => $access_type){
                $aco_record = $aco->findById($aco_id);
                $model_plural = Inflector::pluralize($aco_record['Aco']['model']);
                if($access_type == 'allow'){
                    $this->Acl->allow($aro_alias, $model_plural.'/'.$aco_record[ 'Aco' ][ 'alias' ], '*');
                }
                elseif($access_type == 'deny'){
                    $this->Acl->deny($aro_alias, $model_plural.'/'.$aco_record[ 'Aco' ][ 'alias' ], '*');
                }
            }
            $this->Session->setFlash(__('Security Changes has been saved', true));
            $this->redirect(array('action'=>'index'));
        }
        // lets gather the aco selections available
        $aco =& $this->Acl->Aco;
        // list the whole tree & the details of the Aco records
        $aco_tree = $aco->generateTreeList();
        $aco_records = $aco->find('all');

        $acos = array();
        $current_alias = $this->Group->name.':'.$id;
        foreach($aco_tree as $item){
            $aco_selected = '';
            $aco_id = str_replace('_', '', $item);
            $aco_type = preg_match('/_/', $item) ? 'action' : 'controller';
            foreach($aco_records as $aco){
                if($aco['Aco']['id'] == $aco_id){
                    /* generate alias, different for controller and action ACO
                     in which, controller alias is Pluralized{ControllerName},
                    and action alias {ControllerName}.{ActionName} */
                    $aco_alias = $aco_type == 'controller'
                        ? $aco['Aco']['alias']
                        : /*$aco['Aco']['model'] .'.'. */$aco['Aco']['alias'];
                    /* check if the current item is allowed or denied */
                    $aros = $aco['Aro'];
                    foreach($aros as $aro){
                        if($aro['alias'] == $current_alias){
                            if(($aro[ 'Permission' ][ '_create' ] == 1) &&
                                ($aro[ 'Permission' ][ '_read' ] == 1) &&
                                ($aro[ 'Permission' ][ '_update' ] == 1) &&
                                ($aro[ 'Permission' ][ '_delete' ] == 1)){
                                //debug("Allowed action {$current_alias} : {$alias}");
                                $aco_selected = 'allow';
                                break;
                            }else{
                                //debug("Denied action {$current_alias} : {$alias}");
                                $aco_selected = 'deny';
                                break;
                            }
                        }
                    }
                    break;
                }
            }
            $acos[] = array(
                'id' =>$aco_id,
                'type'=>$aco_type,
                'alias'=>$aco_alias,
                'selected'=>$aco_selected);
        }
        $this->set('acos', $acos);
        /* query for Group to security */
        if(empty($this->data)){
            $this->data = $this->Group->read(null, $id);
        }
    }
}
?>